import 'dart:convert';
import 'package:http/http.dart' as http;
import '../models/wiki_config.dart';
import '../services/config_service.dart';

class WikiApiProvider {
  static const String _baseUrl = 'https://api.example.com'; // 预留API接口
  static const Duration _timeout = Duration(seconds: 30);
  final ConfigService _configService = ConfigService();

  // 获取所有Wiki站点列表
  Future<List<WikiItem>> getAllWikiSites() async {
    try {
      final config = await _configService.getWikiConfig();
      return config.wikis;
    } catch (e) {
      throw Exception('Failed to fetch wiki sites: $e');
    }
  }

  // 搜索Wiki站点
  Future<List<WikiItem>> searchWikiSites(String query) async {
    try {
      final allSites = await getAllWikiSites();
      return allSites
          .where((site) =>
              site.name.toLowerCase().contains(query.toLowerCase()) ||
              site.description.toLowerCase().contains(query.toLowerCase()))
          .toList();
    } catch (e) {
      throw Exception('Failed to search wiki sites: $e');
    }
  }

  // 获取特定Wiki的内容（预留接口）
  Future<String> getWikiContent(String wikiId, String pageId) async {
    try {
      final response = await http.get(
        Uri.parse('$_baseUrl/wiki/$wikiId/page/$pageId'),
        headers: {'Content-Type': 'application/json'},
      ).timeout(_timeout);

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        return data['content'] ?? '';
      } else {
        throw Exception('HTTP ${response.statusCode}: ${response.body}');
      }
    } catch (e) {
      throw Exception('Failed to fetch wiki content: $e');
    }
  }


}
